/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-09 09:09:41
 * @LastEditTime: 2023-11-02 09:54:26
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { ViewIcon, ViewOffIcon } from '@chakra-ui/icons';
import {
  Box,
  Button,
  Flex,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Heading,
  Input,
  InputGroup,
  InputRightElement,
  Link,
  Stack,
  Text,
  useColorModeValue,
  useToast,
} from '@chakra-ui/react';
import { Field, FieldProps, Formik } from 'formik';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link as ReactRouterLink, useNavigate } from 'react-router-dom';

import userService from '@/api/user.service';
export default function ForgotPasswordForm(): JSX.Element {
  const { t } = useTranslation();
  const toast = useToast();
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();

  const handleReset = async (values: any) => {
    setIsLoading(true);
    try {
      const { code } = await userService.resetPassword(values);
      setIsLoading(false);
      if (Number(code) === 200) {
        toast({
          position: 'top',
          description: '密码已修改，请重新登录！',
          status: 'success',
          duration: 3000,
          isClosable: true,
        });
        navigate('/signin');
      }
    } catch (e) {
      console.log(e);
      setIsLoading(false);
    }
  };
  return (
    <Flex align="center" justify="center">
      <Stack spacing={8} mx="auto" maxW="lg" minW={{ md: 'md' }} py={12} px={6}>
        <Box
          rounded="lg"
          bg={useColorModeValue('white', 'base.800')}
          boxShadow="lg"
          p={8}
        >
          <Heading
            lineHeight={1.1}
            textAlign="center"
            mb="4"
            fontSize={{ base: '2xl', md: '3xl' }}
          >
            {t('auth.forgetPass')}
          </Heading>
          <Formik
            initialValues={{
              username: '',
              mobile: '',
              newPassword: '',
            }}
            onSubmit={(values) => {
              handleReset(values);
            }}
          >
            {({ handleSubmit, errors, touched }) => (
              <form onSubmit={handleSubmit}>
                <Stack spacing={4}>
                  <Field
                    name="username"
                    validate={(value: string) => {
                      let error;
                      if (!value) {
                        error = t('auth.usernameRequired');
                      }
                      return error;
                    }}
                  >
                    {({ field }: FieldProps) => (
                      <FormControl
                        isRequired
                        isInvalid={Boolean(errors.username && touched.username)}
                      >
                        <FormLabel fontWeight="600" htmlFor="username">
                          {t('profile.username')}
                        </FormLabel>
                        <Input
                          id="username"
                          type="text"
                          variant="filled"
                          {...field}
                          placeholder={t('auth.usernamePlaceholder')}
                        />
                        <FormErrorMessage>
                          {errors.username as string}
                        </FormErrorMessage>
                      </FormControl>
                    )}
                  </Field>
                  <Field
                    name="mobile"
                    validate={(value: string) => {
                      let error;
                      if (!value) {
                        error = t('auth.mobileRequired');
                      }
                      if (value && !/^1[3456789]\d{9}$/.test(value)) {
                        error = t('auth.invalidMobile');
                      }
                      return error;
                    }}
                  >
                    {({ field }: FieldProps) => (
                      <FormControl
                        isRequired
                        isInvalid={Boolean(errors.mobile && touched.mobile)}
                      >
                        <FormLabel fontWeight="600" htmlFor="mobile">
                          {t('profile.mobile')}
                        </FormLabel>
                        <Input
                          id="mobile"
                          type="text"
                          variant="filled"
                          {...field}
                          placeholder={t('auth.mobilePlaceholder')}
                        />
                        <FormErrorMessage>
                          {errors.mobile as string}
                        </FormErrorMessage>
                      </FormControl>
                    )}
                  </Field>
                  <Field
                    name="newPassword"
                    validate={(value: string) => {
                      let error;
                      if (value.length < 6) {
                        error = t('auth.passwordLength');
                      }
                      return error;
                    }}
                  >
                    {({ field }: FieldProps) => (
                      <FormControl
                        isRequired
                        isInvalid={Boolean(
                          errors.newPassword && touched.newPassword
                        )}
                      >
                        <FormLabel fontWeight="600" htmlFor="newPassword">
                          {t('auth.newPassword')}
                        </FormLabel>

                        <InputGroup>
                          <Input
                            id="newPassword"
                            type={showPassword ? 'text' : 'password'}
                            variant="filled"
                            {...field}
                            placeholder={t('auth.newPasswordPlaceholder')}
                          />
                          <InputRightElement
                            cursor="pointer"
                            onClick={() => setShowPassword(!showPassword)}
                          >
                            {!showPassword ? <ViewOffIcon /> : <ViewIcon />}
                          </InputRightElement>
                        </InputGroup>
                        <FormErrorMessage>
                          {errors.newPassword as string}
                        </FormErrorMessage>
                      </FormControl>
                    )}
                  </Field>
                  <Stack spacing={6} pt="3">
                    <Button type="submit" isLoading={isLoading} bg="base.700">
                      {t('auth.resetPassword')}
                    </Button>
                  </Stack>
                </Stack>
              </form>
            )}
          </Formik>
          <Stack pt={6}>
            <Text align="center">
              {t('common.back')}{' '}
              <Link as={ReactRouterLink} color="blue.400" to="/signin">
                {t('auth.signin')}
              </Link>
            </Text>
          </Stack>
        </Box>
      </Stack>
    </Flex>
  );
}
